package com.superjson.showpro.controller;

import com.alibaba.fastjson.JSONObject;
import com.beantools.filters.BuilderFilters;
import com.superjson.showpro.controller.core.BaseContoller;
import com.superjson.showpro.entity.Comment;
import com.superjson.showpro.entity.User;
import com.superjson.showpro.service.CommentService;
import com.superjson.showpro.shared.enums.CommentTypeEnum;
import com.superjson.showpro.shared.result.Result;
import com.superjson.showpro.shared.result.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static com.beantools.util.ObjectUtil.isNull;
import static com.beantools.util.StringUtil.isBlank;
import static com.superjson.showpro.constants.SessionConstant.TOKEN;
import static com.superjson.showpro.shared.result.ResultCodeEnum.EMPTY_CONTENT;
import static com.superjson.showpro.shared.result.ResultCodeEnum.USER_NO_LOGIN;
import static com.superjson.showpro.shared.util.CommonUtil.ifTrueThrow;

/**
 * Created By zby on 19:59 2019/5/22
 */
@RestController("commentController")
@RequestMapping("/comment")
public class CommentController extends BaseContoller {

    @Autowired
    private CommentService commentService;

    /**
     * Created By zby on 19:03 2019/6/13
     * 保存评论
     */
    @RequestMapping(value = "/save", method = RequestMethod.GET)
    public Result saveComment(String content, Long articleId, Long userId, CommentTypeEnum commentType, HttpServletRequest request) {
        String session = (String) request.getSession().getAttribute(TOKEN);
        User user = getUser(request).getResultData();
        ifTrueThrow(isNull(session) || isNull(session) || !user.getToken().equalsIgnoreCase(session), USER_NO_LOGIN);
        commentService.saveComment(content, articleId, user.getId(), commentType);
        List<Comment> comments = commentService.listComment(userId, articleId).getResultData();
        return ResultUtil.buildSuccess(getResult(comments));
    }

    /**
     * Created By zby on 20:18 2019/6/13
     * 根据文章的id或用户id获取评论
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listComment(Long articleId) {
        List<Comment> comments = commentService.listComment(articleId).getResultData();
        return ResultUtil.buildSuccess(getResult(comments));
    }

    private Result getResult(List<Comment> comments) {
        String[] commentJson = {"id", "content", "createDatetime", "user.phone:userPhone"};
        ArrayList<JSONObject> list = BuilderFilters.builderPropertyFilters().filterJsons(commentJson, comments);
        return ResultUtil.buildSuccess(list);
    }
}
